package gatecontrol.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.xkh.xkh.R;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import gatecontrol.network.beans.GateUpLoad;
import gatecontrol.network.beans.SluiceControl;
import gatecontrol.network.http.SendGateControl;

import com.xkh.xkh.MyApplication;

import managers.UIHandler;
import managers.UserInfo;
import model.OwnUser;
import shuiyuqing.model.BasicInfoModel;

/**
 * 闸门控制界面
 * Created by nimi on 2015/11/4.
 */
public class GateSendActivity extends UIHandler.BaseActivity {
    private Button back_gate_send;
    private Button send;
    private Button btn_worker;
    //    private RadioButton up;
//    private RadioButton down;
    private TextView tv_gatename;
    private RelativeLayout v_gatenum1;
    private TextView tv_gatenum11;
    private EditText et_gatenum12;
    private Switch swt_aSwitch1;
    private RelativeLayout v_gatenum2;
    private TextView tv_gatenum21;
    private EditText et_gatenum22;
    private Switch swt_aSwitch2;
    private RelativeLayout v_gatenum3;
    private TextView tv_gatenum31;
    private EditText et_gatenum32;
    private Switch swt_aSwitch3;
    private RelativeLayout v_gatenum4;
    private TextView tv_gatenum41;
    private EditText et_gatenum42;
    private Switch swt_aSwitch4;
    private RelativeLayout v_gatenum5;
    private TextView tv_gatenum51;
    private EditText et_gatenum52;
    private Switch swt_aSwitch5;
    private static final int gate_level_DECIMAL_DIGITS = 3;

    private GateUpLoad gateUpLoad = new GateUpLoad();
    int hole;//闸门数

    String name;// 闸门名称
    String scode;// 测站编码
    String gateCode; // 水闸编码

    OwnUser ownUser = MyApplication.getOwnUser();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.acitivity_gate_con_send);
        InputFilter lengthfilter1 = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                if ("".equals(source.toString())) {
                    return null;
                }
                String dValue = dest.toString();
                System.out.println(dValue);
                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1) {
                    String dotValue = splitArray[1];

                    int diff = dotValue.length() + 1 - gate_level_DECIMAL_DIGITS;
                    if (diff > 0) {

                        return source.subSequence(start, end - diff);
                    }
                } else {
                    String sIntegValue = splitArray[0];
                    int diff = sIntegValue.length() - 9;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                }
                return null;
            }
        };
        v_gatenum1 = (RelativeLayout) findViewById(R.id.gatenum1);
        tv_gatenum11 = (TextView) findViewById(R.id.gatenum11);
        et_gatenum12 = (EditText) findViewById((R.id.gatenum12));
        et_gatenum12.setFilters(new InputFilter[]{lengthfilter1});

        tv_gatenum51 = (TextView) findViewById(R.id.gatenum51);
        et_gatenum52 = (EditText) findViewById((R.id.gatenum52));
        et_gatenum52.setFilters(new InputFilter[]{lengthfilter1});

        tv_gatenum41 = (TextView) findViewById(R.id.gatenum41);
        et_gatenum42 = (EditText) findViewById((R.id.gatenum42));
        et_gatenum42.setFilters(new InputFilter[]{lengthfilter1});

        tv_gatenum31 = (TextView) findViewById(R.id.gatenum31);
        et_gatenum32 = (EditText) findViewById((R.id.gatenum32));
        et_gatenum32.setFilters(new InputFilter[]{lengthfilter1});

        tv_gatenum21 = (TextView) findViewById(R.id.gatenum21);
        et_gatenum22 = (EditText) findViewById((R.id.gatenum22));
        et_gatenum22.setFilters(new InputFilter[]{lengthfilter1});

        v_gatenum2 = (RelativeLayout) findViewById(R.id.gatenum2);
        v_gatenum3 = (RelativeLayout) findViewById(R.id.gatenum3);
        v_gatenum4 = (RelativeLayout) findViewById(R.id.gatenum4);
        v_gatenum5 = (RelativeLayout) findViewById(R.id.gatenum5);

        swt_aSwitch1 = (Switch) findViewById(R.id.id_switch_gate1);
        swt_aSwitch2 = (Switch) findViewById(R.id.id_switch_gate2);
        swt_aSwitch3 = (Switch) findViewById(R.id.id_switch_gate3);
        swt_aSwitch4 = (Switch) findViewById(R.id.id_switch_gate4);
        swt_aSwitch5 = (Switch) findViewById(R.id.id_switch_gate5);


        //动态显示闸门
        Bundle bundle = this.getIntent().getExtras();
        hole = (int) bundle.getFloat("num");
        name = bundle.getString("name");
        scode = bundle.getString("Scode");//测站编码
        gateCode = bundle.getString("gateCode");//水闸编码
        gateUpLoad.setStadia_code(scode);
        gateUpLoad.setGate_num(gateCode);
        tv_gatename = (TextView) findViewById(R.id.gatename);
        tv_gatename.setText(name);
        switch (hole) {
            case 5:
                v_gatenum5.setVisibility(View.VISIBLE);

            case 4:
                v_gatenum4.setVisibility(View.VISIBLE);

            case 3:
                v_gatenum3.setVisibility(View.VISIBLE);

            case 2:
                v_gatenum2.setVisibility(View.VISIBLE);

                break;
            default:
                break;
        }


        //记录操作方式   1上升  0下降
//        up = (RadioButton) findViewById(R.id.upButton);
//        up.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                gateUpLoad.setCon_way('1');
//            }
//        });
//        down = (RadioButton) findViewById(R.id.downButton);
//        down.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                gateUpLoad.setCon_way('0');
//            }
//        });
        send = (Button) findViewById(R.id.check);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 检查输入是否符合要求

                if (!ownUser.getUser_Role().equals(UserInfo.USEROPER_MOD02)) {
                    Toast.makeText(GateSendActivity.this, "对不起,您的权限不够", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!checked()) {
                    return;
                } else {
                    new AlertDialog.Builder(GateSendActivity.this).setTitle("确认发送")
                            .setMessage(getSendMessage()).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            sendCommand();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                }


            }
        });

        btn_worker = (Button) findViewById(R.id.id_btn_woker);
        btn_worker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                RequstLocation.Upload upload = new RequstLocation.Upload();
//                upload.setAsker(UserInfo.getUserName());
//                upload.setGateId(gateCode);
//                new RequstLocation(upload, new RequstLocation.Delegate() {
//                    @Override
//                    public void onResponse(String response, RequstLocation requstLocation) {
//                        if (requstLocation.getDownload().getStatus() == RequstLocation.Download.SUCCESS)
//                        {
//
//                        }
//                        else if (requstLocation.getDownload().getStatus() == RequstLocation.Download.NOTONLINE)
//                        {
//                            Toast.makeText(GateSendActivity.this,"此工作人员不在线",Toast.LENGTH_SHORT).show();
//                        }
//                        else if (requstLocation.getDownload().getStatus() == RequstLocation.Download.FAILED)
//                        {
//                            Toast.makeText(GateSendActivity.this,"发送失败",Toast.LENGTH_SHORT).show();
//                        }
//                    }
//
//                    @Override
//                    public void onError(VolleyError error, RequstLocation requstLocation) {
//
//                    }
//                }).get();
            }
        });

    }

    // 发送命令
    public void sendCommand() {
        List<Part> command = sendGateControl();
        gateUpLoad.setCommand(command);
        Calendar time = Calendar.getInstance();
        gateUpLoad.setSend_time(time);//设置时间
        String person = ownUser.getUser_RealName();
        gateUpLoad.setSend_person(person);

        SendGateControl.UploadSluiceControlData upload = new SendGateControl.UploadSluiceControlData();
        SluiceControl sc = new SluiceControl();
        upload.setSc(sc);

        sc.setSendCommand(JSON.toJSONString(command));
        sc.setSendPerson(person);
        sc.setSendTime(time);
        sc.setStadiaCode(gateUpLoad.getStadia_code());
        sc.setWatergateCode(gateUpLoad.getGate_num());
        SendGateControl send = new SendGateControl(null, upload);
        send.send();

        // 根据闸门选择获取此闸门的管理人员的号码

        String number = BasicInfoModel.getPhoneNumber(gateCode);

        if (number != null && number.trim().length() != 0)
        {
            StringBuffer body = new StringBuffer();
            body.append("发送人："+ownUser.getUser_RealName()+"\n");
            body.append("水闸名称："+name+"\n");
            body.append(getSendMessage());

            // 发送短信
            Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
            sendIntent.setData(Uri.parse("smsto:"+number));
            sendIntent.putExtra("sms_body",body.toString());
            startActivity(sendIntent);
        }
        else
        {
            Toast.makeText(this,"此闸门未指定管理员联系电话",Toast.LENGTH_SHORT).show();
        }


    }


    // 检查闸门命令输入是否符合要求
    private boolean checked() {

        switch (hole) {
            case 1:
                if (et_gatenum12.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "1号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }
                break;


            case 2:
                if (et_gatenum12.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "1号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum22.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "2号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }
                break;

            case 3:

                if (et_gatenum12.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "1号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum22.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "2号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum32.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "3号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }
                break;
            case 4:

                if (et_gatenum12.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "1号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum22.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "2号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum32.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "3号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum42.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "4号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }
                break;
            case 5:

                if (et_gatenum12.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "1号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum22.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "2号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum32.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "3号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum42.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "4号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (et_gatenum52.getText().toString().isEmpty()) {
                    Toast.makeText(MyApplication.share(), "5号闸门不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }
                break;
//            case 0:
            default:
                break;
        }

        return true;
    }

    public String getSendMessage() {
        StringBuffer reslut = new StringBuffer();
        switch (hole) {
            case 1:
                reslut.append("1号闸门:").append(format2(et_gatenum12, swt_aSwitch1)).append(";").append("\n");
                break;
            case 2:
                reslut.append("1号闸门:").append(format2(et_gatenum12, swt_aSwitch1)).append(";").append("\n");
                reslut.append("2号闸门:").append(format(et_gatenum22, swt_aSwitch2)).append(";").append("\n");
                break;
            case 3:
                reslut.append("1号闸门:").append(format2(et_gatenum12, swt_aSwitch1)).append(";").append("\n");
                reslut.append("2号闸门:").append(format2(et_gatenum22, swt_aSwitch2)).append(";").append("\n");
                reslut.append("3号闸门:").append(format(et_gatenum32, swt_aSwitch3)).append(";").append("\n");
                break;
            case 4:
                reslut.append("1号闸门:").append(format2(et_gatenum12, swt_aSwitch1)).append(";").append("\n");
                reslut.append("2号闸门:").append(format2(et_gatenum22, swt_aSwitch2)).append(";").append("\n");
                reslut.append("3号闸门:").append(format2(et_gatenum32, swt_aSwitch3)).append(";").append("\n");
                reslut.append("4号闸门:").append(format2(et_gatenum42, swt_aSwitch4)).append(";").append("\n");
                break;
            case 5:
                reslut.append("1号闸门:").append(format2(et_gatenum12, swt_aSwitch1)).append(";").append("\n");
                reslut.append("2号闸门:").append(format2(et_gatenum22, swt_aSwitch2)).append(";").append("\n");
                reslut.append("3号闸门:").append(format2(et_gatenum32, swt_aSwitch3)).append(";").append("\n");
                reslut.append("4号闸门:").append(format2(et_gatenum42, swt_aSwitch4)).append(";").append("\n");
                reslut.append("5号闸门:").append(format2(et_gatenum52, swt_aSwitch5)).append(";").append("\n");
                break;
            default:
                break;

        }


        return reslut.toString();
    }

    // 得到格式化数据
    @Deprecated
    private String format(EditText editText, Switch aSwitch1) {
        StringBuffer stringBuffer = new StringBuffer();
        if (aSwitch1.isChecked()) {
            stringBuffer.append("开");
        } else {
            stringBuffer.append("关");
        }
        stringBuffer.append(editText.getText().toString()).append("厘米");
        return stringBuffer.toString();
    }


    // 得到格式化数据
    private String format2(EditText editText, Switch aSwitch1) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("开到");
        stringBuffer.append(editText.getText().toString()).append("厘米");
        return stringBuffer.toString();
    }


    public List<Part> sendGateControl() {//闸控命令格式
        List<Part> controlcommand = new ArrayList<Part>();
        Part part = FillPart(et_gatenum12, swt_aSwitch1, 1);
        controlcommand.add(part);
        switch (hole) {
            case 5:
                part = FillPart(et_gatenum52, swt_aSwitch5, 5);
                controlcommand.add(part);
            case 4:
                part = FillPart(et_gatenum42, swt_aSwitch4, 4);
                controlcommand.add(part);
            case 3:
                part = FillPart(et_gatenum32, swt_aSwitch3, 3);
                controlcommand.add(part);
            case 2:
                part = FillPart(et_gatenum22, swt_aSwitch2, 2);
                controlcommand.add(part);
            default:
                break;
        }
        return controlcommand;

    }

    public Part FillPart(TextView v, Switch aSwitch, int n) {
        Part part = new Part();
        part.setN(n);
        if (aSwitch.isChecked())
            part.setB(new BigDecimal(v.getText().toString()));
        else {
            BigDecimal d = new BigDecimal(v.getText().toString());
            d = d.multiply(new BigDecimal(-1));
            part.setB(d);
        }
        return part;
    }

    // 每个闸门的命令
    public static class Part {
        // 闸门编号 1-5
        int n;
        // 上升，下降尺度
        BigDecimal b;

        public int getN() {
            return n;
        }

        public void setN(int n) {
            this.n = n;
        }

        public BigDecimal getB() {
            return b;
        }

        public void setB(BigDecimal b) {
            this.b = b;
        }
    }


}
